//
//  ZSRefresh.swift
//  ZSWeibo
//
//  Created by zsj1992 on 16/4/16.
//  Copyright © 2016年 ichange. All rights reserved.
//

import UIKit


//定义一个枚举描述刷新控件的当前状态

enum ZSRefreshState : Int {
    case Normal = 0 //正常状态
    case Pulling = 1//正在拖拽的状态
    case Refreshing = 2//正在拖拽的状态
}

/// 自定义的下拉刷新控件
class ZSRefresh: UIControl {

    /**释放的时候移除观察者*/
     deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset", context: nil)
    }

    /**懒加载子视图-->箭头+菊花+文案*/
    
    private lazy var arrowView : UIImageView = {
        let arrowView = UIImageView()
        arrowView.image = UIImage(named: "tableview_pull_refresh")
        arrowView.sizeToFit()
        return arrowView
    }()
    
    private lazy var indicator : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    private lazy var lblContent : UILabel = {
        let lbl = UILabel()
        lbl.text = "自定义刷新控件"
        return lbl
    }()
    
    //用一个滚动视图保存refresh所保存到的父视图--
    var scrollView : UIScrollView?
    
  
    //保存刷新状态的属性
    var refreshState:ZSRefreshState = .Normal{
    //已经设置了状态
        didSet{
        
            switch refreshState{
            
            case .Normal :
                lblContent.text = "下拉起飞"
                indicator.stopAnimating()
                arrowView.hidden = false
                
                
                
                //上一次的状态是 刷新状态  再减
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top = inset.top - 64
                        self.scrollView?.contentInset = inset
                    })
                    
                }

                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })

            
            case.Pulling:
                lblContent.text = "马上起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
           
            
            case.Refreshing:
                lblContent.text = "正在飞ing..."
                indicator.startAnimating()
                arrowView.hidden = true
                sendActionsForControlEvents(.ValueChanged)
                
                //修改contentInset.top
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top = inset.top + 64
                    self.scrollView?.contentInset = inset
                })


            }
        }
    }
    
    
    
    /**重写初始化方法*/
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        //背景色
        backgroundColor = UIColor.yellowColor()
        setupUI()
        
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func setupUI(){
        
        indicator.startAnimating()
        
        addSubview(arrowView)
        addSubview(indicator)
        addSubview(lblContent)
    
        arrowView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-50)
            make.centerY.equalTo(self)
        }
        
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowView)
        }
        
        lblContent.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowView.snp_right)
            make.centerY.equalTo(arrowView)
        }
    }
    
    
    
    
    //停止刷新,先停止刷新
    
    func endRefreshing(){
        
        let delta = dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 0.9))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.refreshState = .Normal
        }
    
    }
    
    
    
}


// MARK: - 类扩展 -->利用kvo模式监听刷新控件所添加到的tableView的拖拽
extension ZSRefresh{
    //将要移动到父控件上面-->>>监听父控件的 属性变化
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //fresh控件去监听父控件的contentOffset的变化
        
        if let fatherView = newSuperview as? UIScrollView{
        
            scrollView = fatherView
            
            fatherView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            

        }
    }
    

    //实现作为观察者应该实现的监听观察对象属性变化方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        print(scrollView!.contentOffset.y)
        
        let offsetY = scrollView?.contentOffset.y

//        if scrollView!.dragging{
//        
//        //进行判断,改变刷新控件的状态
//        let offsetY = scrollView?.contentOffset.y
//        
//        
//        if refreshState == .Normal && offsetY < -128
//        {
//            refreshState = .Pulling
//            
//        }else if refreshState == .Pulling && offsetY > -128
//        {
//            refreshState = .Refreshing
//            indicator.startAnimating()
//            arrowView.hidden = true
//            
//        }
//        else{
//        
//            refreshState = .Normal
//            
//        }
//        
//    }

        
        if (scrollView!.dragging){
        
            if refreshState == .Pulling && offsetY > -128 {
                //只要满足 位移 大于 -124 并且 当前状态是 准备刷新刷新状态
                print("普通状态")
                refreshState = .Normal
            } else if  refreshState == .Normal && offsetY < -128 {
                print("准备刷新刷新状态")
                refreshState = .Pulling
            }
        }
                
         else {
            //没有拽动tableView && 当前状态是 准备刷新状态 才修改为 正在刷新状态
            if refreshState == .Pulling {
                print("正在刷新")
                refreshState = .Refreshing
                //转动小菊花
                indicator.startAnimating()
                //隐藏箭头
                arrowView.hidden = true
            }
            
        }

    
    }
        
        
        
        
        
        
        
        
}
    






